
#include "Generator.h"
#include "Symbols.h"
#include "util.h"

//#include <cctype>


using namespace codegen;
using namespace resip;
using namespace std;


#define RESIPROCATE_SUBSYSTEM LogSystem::LOGMODULE


//////////////////////////////////////////////////////////////////////////
Generator::Generator(const resip::Data& class_name, const resip::Data& base_class_name /*= resip::Data::Empty*/)
    : formed_(false), parsed_(false)
    , class_name_(class_name)
    , base_class_name_(base_class_name)
{
}

Generator::~Generator()
{
}

bool Generator::is_well_formed() const
{
    try
    {
        check_parsed();
    }
    catch (...)
    {
    }

    return formed_;
}

EncodeStream& Generator::encode(EncodeStream& ostm) const
{
    if(!is_well_formed())
        return ostm;

    return this->encode_all(ostm);
}

void Generator::check_parsed() const
{
    if (!parsed_) do_parse();
}

void Generator::do_parse() const
{
    Generator* ncThis = const_cast<Generator*>(this);
    ncThis->parsed_ = true;
    ncThis->formed_ = false;
    ncThis->formed_ = ncThis->parse();
}

EncodeStream& Generator::encode_all(EncodeStream& ostm) const
{
    this->encode_header(ostm);
    this->encode_class(ostm);
    this->encode_footer(ostm);
    return ostm;
}

EncodeStream& Generator::encode_header(EncodeStream& ostm) const
{
    return ostm << "#ifndef " << class_name_ << "_HEADER" << Symbols::LF
        << "#define " << class_name_ << "_HEADER" << Symbols::LF;
}

EncodeStream& Generator::encode_footer(EncodeStream& ostm) const
{
    return ostm << "#endif // " << "#ifndef " << class_name_ << "_HEADER" << Symbols::LF;
}

void Generator::add_error(const resip::Data& reason, const Node* node /*= 0*/)
{
    errors_ += reason;
    if (node)
    {
        errors_ += " - ";
        errors_ += node->key_;
    }
    errors_ += "\n";
}


